package com.example.question.array;

import java.util.Arrays;

public class Code13_238 {

    public static void main(String[] args) {
        Code13_238 code = new Code13_238();
        int[] ints = code.productExceptSelf(new int[]{1, 2, 3, 4});
        System.out.println(Arrays.toString(ints));
    }

    /**
     * 前缀积
     * 后缀积
     */
    public int[] productExceptSelf(int[] nums) {
        int[] prefixMulti = new int[nums.length];
        int[] suffixMulti = new int[nums.length];
        prefixMulti[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            prefixMulti[i] = nums[i] * prefixMulti[i - 1];
        }

        suffixMulti[nums.length - 1] = nums[nums.length - 1];
        for (int i = nums.length - 2; i >= 0; i--) {
            suffixMulti[i] = nums[i] * suffixMulti[i + 1];
        }

        int[] res = new int[nums.length];
        res[0] = suffixMulti[1];
        res[nums.length - 1] = prefixMulti[nums.length - 2];
        for (int i = 1; i < nums.length - 1; i++) {
            res[i] = prefixMulti[i - 1] * suffixMulti[i + 1];
        }
        return res;
    }
}
